import { defineStore } from 'pinia'

export const useMainStore = defineStore('main', {
  state: () => ({
    curView: sessionStorage.getItem('navView'),
    weather: JSON.parse(localStorage.getItem('weather')) || {},
    userdata: JSON.parse(localStorage.getItem('userdata')) || {},
    // 新增文章相关的状态
    buyList: [],
    sellList: [],
    currentArticle: null,
    //记录当前展示分页
    currentPage: 1,
    //记录产品集市当前展示的类型
    activeTap: 'sell',
    //记录政府收购当前展示的分类
    activeGov: 'buy',
  }),
  
  actions: {
    changeView(num) {
      this.curView = num;
    },
    saveWeather(data) {
      this.weather = data;
      localStorage.setItem('weather', JSON.stringify(data));
    },
    saveUserData(data) {
      const userInfo = { ...data }
      delete userInfo.token
      this.userdata = userInfo;
      localStorage.setItem('userdata', JSON.stringify(userInfo));
    },
    // 拆分成两个独立的 action
    setBuyList(buyList) {
      this.buyList = buyList;
    },
    setSellList(sellList) {
      this.sellList = sellList;
    },
    setCurrentArticle(article) {
      this.currentArticle = article;
    },
    findArticleById(id) {
      return [...this.buyList, ...this.sellList].find(item => item.article_id === parseInt(id));
    },
    addArticle(article, type) {
      if(type === 'buy') {
        this.buyList.unshift(article);
      } else {
        this.sellList.unshift(article);
      }
    },

    //保存当前分页
    setCurrentPage(page) {
      this.currentPage = page;
    },
    //保存当前类型
    setActiveTap(tap) {
      this.activeTap = tap;
    },
    setActiveGov(tap) {
      this.activeGov = tap;
    },
  }
})